import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, Empty, Popconfirm, Table } from 'antd';
import { FormInstance } from 'antd/lib';

import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { roleCancelBind } from '@/services/base/jiaoseguanlijiaosexiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';

import Link, { LinkRef } from './link-modal';

export type BizObject = BASE.RoleDataPermission;

export type UserProps = {
  role?: BASE.Role;
};

const User: React.FC<UserProps> = ({ role }) => {
  const permission = usePermission();
  const link = useRef<LinkRef>(null);
  const filter = useRef<FormInstance>();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData } = {}) => {
      if (!role?.id) {
        return {
          list: [],
          total: 0
        };
      }

      const res = await orgUserInfoVoPage({
        ...formData,
        ...id,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序,
        roleId: role?.id
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter.current,
      refreshDeps: [role]
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  if (!role) {
    return <Empty description="请选择角色" />;
  }

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        formRef={filter}
        extra={
          <>
            <Button
              onClick={() => {
                link.current?.open({
                  role: role,
                  list: table?.data?.list || [],
                  onSuccess: () => {
                    table.refresh();
                  }
                });
              }}
              type="primary"
            >
              关联员工
            </Button>
          </>
        }
      >
        <Filter.Item name="id">
          <SearchInput
            style={{
              width: 120 * 3
            }}
            typeList={[
              { value: 'username', children: '用户名' },
              { value: 'fullName', children: '用户姓名' }
            ]}
          />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      <Table<BASE.OrgUserInfoVOduixiang>
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 80,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '用户名',
            dataIndex: 'username'
          },
          {
            title: '姓名',
            dataIndex: 'fullName'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  <Popconfirm
                    title={`确定删除该角色吗？`}
                    onConfirm={async () => {
                      const res = await roleCancelBind({
                        id: role.id as unknown as number,
                        manyIds: row.id as unknown as string
                      });

                      store.app?.message.success(res.message);
                      table.refresh();

                      return res.success;
                    }}
                  >
                    <Text type="danger">移除当前角色</Text>
                  </Popconfirm>
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />

      <Link ref={link} />
    </>
  );
};

export default User;
